﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using System.ServiceProcess;

using PersistenceObject.Framework;
using PersistenceObject.Framework.Expressions;

using FundSms.Server.Model;
using FundSms.SmsLib;

namespace FundSms.Server.Report
{
    public class Program : ServiceBase
    {
        private static readonly string DataKey = "Sms";

        //企业列表
        private static IList<Enterprise> Enterprises;

        //定时清理控制台
        private static System.Timers.Timer timerConsole = new System.Timers.Timer();
        //定时更新企业数据
        private static System.Timers.Timer timerEnterprise = new System.Timers.Timer();


        private static int RefreshConsoleTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshConsoleTime"]) * 1000;
        private static int RefreshEnterpriseTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshEnterpriseTime"]) * 1000;

        private static int SleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
        private static int TransferSmsCount = Convert.ToInt32(ConfigurationManager.AppSettings["TransferSmsCount"]);
        private static int SupportEnterpriseCount = Convert.ToInt32(ConfigurationManager.AppSettings["SupportEnterpriseCount"]);

        private static int Debug = 0;

        private static string ServiceRealName = ConfigurationManager.AppSettings["ServiceName"];
        private static string ServiceDisPlayName = ConfigurationManager.AppSettings["ServiceDisPlayName"];
        private static string ServiceDescription = ConfigurationManager.AppSettings["ServiceDescription"];

        private static bool LogToFile = ConfigurationManager.AppSettings["LogToFile"] == "1" ? true : false;

        private static object obj = new object();

        //定义发送线程
        private static Thread[] LogThreads;
        //当前的企业数
        private static int CurrentEnterpriseCount;
        //是否处于停止服务状态下
        private static bool Stopped = false;
        //判断每个线程是否已经跳出循环
        private static Dictionary<string, bool> ThreadStatus = new Dictionary<string, bool>();

        //服务所在路径
        private static string ServicePath = Application.ExecutablePath;
        private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);

        #region 应用程序入口
        static void Main(string[] args)
        {
            Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            bool exists = ServiceControl.CheckService(ServiceRealName);

            if (args.Length == 0)
            {
                ServiceBase.Run(new ServiceBase[] { new Program() });
            }
            else
            {
                string parm = args[0].ToLower();

                switch (parm)
                {
                    case "-debug":
                    case "/debug":

                        Debug = 1;

                        if (exists)
                        {
                            ServiceControllerStatus status = ServiceControl.GetServiceStatus(ServiceRealName);

                            if (status != ServiceControllerStatus.Stopped)
                            {
                                Console.WriteLine(GetDateTime() + ServiceRealName + " 服务正在运行，无法进入调试状态。请先停止该服务");
                                Console.ReadLine();
                            }
                            else
                            {
                                InitilizeCompoment();
                            }
                        }
                        else
                        {
                            InitilizeCompoment();
                        }


                        break;

                    case "-install":
                    case "-setup":
                    case "/install":
                    case "/setup":

                        if (exists)
                        {
                            Console.WriteLine(GetDateTime() + ServiceRealName + " 服务已经存在，如果您想升级服务，请先卸载该服务");
                            Console.ReadLine();
                        }
                        else
                        {
                            Console.WriteLine(GetDateTime() + ServicePath);

                            bool result = ServiceControl.InstallService(ServicePath, ServiceRealName, ServiceDisPlayName, ServiceDescription);

                            if (result)
                            {
                                Console.WriteLine(GetDateTime() + "服务安装成功");
                                Console.WriteLine(GetDateTime() + "正在启动服务...");

                                ServiceControl.StartService(ServiceRealName);

                                while (!(ServiceControl.GetServiceStatus(ServiceRealName) == ServiceControllerStatus.Running))
                                {
                                    Thread.Sleep(SleepTime);
                                }

                                Console.WriteLine(GetDateTime() + "服务已经启动");
                            }
                            else
                            {
                                Console.WriteLine(GetDateTime() + "服务安装失败");
                            }

                            Console.ReadLine();
                        }
                        break;

                    case "-uninstall":
                    case "-remove":
                    case "/uninstall":
                    case "/remove":

                        if (!exists)
                        {
                            Console.WriteLine(GetDateTime() + ServiceRealName + " 服务尚未安装");
                        }
                        else
                        {
                            bool result = ServiceControl.UnInstallService(ServiceRealName);

                            if (!result)
                            {
                                Console.WriteLine(GetDateTime() + "服务卸载失败");
                            }
                            else
                            {
                                Console.WriteLine(GetDateTime() + "服务卸载成功");
                            }
                        }

                        Console.ReadLine();

                        break;

                }

            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Output("未处理A：" + e.Exception.Message, ConsoleColor.Red, true);
        }

        static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                Output("未处理P：" + ((System.Exception)e.ExceptionObject).Message, ConsoleColor.Red, true);
            }

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {

            }

            base.Dispose(disposing);
        }

        public Program()
        {
            base.ServiceName = ServiceRealName;
            base.AutoLog = true;
        }

        #endregion

        #region 初始化应用程序
        /// <summary>
        /// 初始化应用程序
        /// </summary>
        private static void InitilizeCompoment()
        {
            if (Debug == 1)
            {
                Console.Title = ServiceDisPlayName;
            }

            //设定用户信息
            Enterprises = GetEnterprise();

            Output("载入初始数据", true);

            //设置初始企业数
            CurrentEnterpriseCount = Enterprises.Count;

            Output("当前企业数：" + CurrentEnterpriseCount, true);

            //初始化定时器
            InitilizeTimer();

            Output("初始化定时器", true);

            //初始化线程
            LogThreads = new Thread[SupportEnterpriseCount];

            ThreadStatus.Clear();

            //初始化线程状态，用于等待线程结束
            foreach (Enterprise enterprise in Enterprises)
            {
                ThreadStatus.Add(enterprise.EnterpriseCode, false);
            }

            int i = 0;

            foreach (Enterprise enterprise in Enterprises)
            {
                LogThreads[i] = new Thread(new ParameterizedThreadStart(Log));
                LogThreads[i].Name = enterprise.EnterpriseCode;
                LogThreads[i].IsBackground = false;
                LogThreads[i].Start(enterprise);

                i++;
            }

            Output("工作线程初始化", true);

            if (Debug == 1)
            {
                Console.ReadLine();
            }
        }
        #endregion

        #region 业务逻辑
        private static void Log(object o)
        {
            Enterprise enterprise = (Enterprise)o;

            IList<MT_TEST> list = null;
            FundSms.Server.Model.Report report = new FundSms.Server.Model.Report();

            string account = enterprise.Account.ToUpper();
            string enterprisecode = enterprise.EnterpriseCode;

            while (true)
            {
                //如果处于停止服务请求下
                if (Stopped)
                {
                    lock (obj)
                    {
                        ThreadStatus[enterprisecode] = true;
                    }
                    //跳出循环
                    break;
                }

                try
                {
                    list = QueryOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + account)).Top(TransferSmsCount).Where((MT_TEST._SmsStatus == 2 | MT_TEST._SmsStatus == -1) & MT_TEST._IsReport == false).OrderBy(MT_TEST._LogID).List();
                }
                catch (Exception e)
                {
                    Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);

                    Thread.Sleep(SleepTime);

                    continue;
                }

                string datechar = DateTime.Now.ToString("yyyy-MM-dd");

                if (list.Count > 0)
                {
                    foreach (MT_TEST test in list)
                    {

                        using (IDataSession ds = new DataSession(DataKey))
                        {
                            ds.Open();

                            try
                            {
                                ds.BeginTran();
                                if (QueryOperate<FundSms.Server.Model.Report>.Create(ds).Where(FundSms.Server.Model.Report._EnterpriseCode == test.EnterpriseCode & FundSms.Server.Model.Report._ReportDay == datechar & FundSms.Server.Model.Report._ChannelCode == test.ChannelCode).Exist())
                                {
                                    if (test.SmsStatus == 2)
                                    {
                                        UpdateOperate<FundSms.Server.Model.Report>.Create(ds).Fields(FieldValue.Create(String.Format("{0}={0}+1", FundSms.Server.Model.Report._SendSuccess))).Where(FundSms.Server.Model.Report._EnterpriseCode == test.EnterpriseCode & FundSms.Server.Model.Report._ReportDay == datechar & FundSms.Server.Model.Report._ChannelCode == test.ChannelCode).Execute();
                                    }
                                    else
                                    {
                                        UpdateOperate<FundSms.Server.Model.Report>.Create(ds).Fields(FieldValue.Create(String.Format("{0}={0}+1", FundSms.Server.Model.Report._SendFailure))).Where(FundSms.Server.Model.Report._EnterpriseCode == test.EnterpriseCode & FundSms.Server.Model.Report._ReportDay == datechar & FundSms.Server.Model.Report._ChannelCode == test.ChannelCode).Execute();
                                    }
                                }
                                else
                                {
                                    report.ChannelCode = test.ChannelCode;
                                    report.EnterpriseCode = test.EnterpriseCode;
                                    report.Ready1 = string.Empty;
                                    report.Ready2 = string.Empty;
                                    report.Ready3 = string.Empty;
                                    report.Ready4 = 0;
                                    report.Ready5 = false;
                                    report.ReportDay = datechar;
                                    report.ReportStatus = 0;

                                    if (test.SmsStatus == 2)
                                    {

                                        report.SendFailure = 0;
                                        report.SendSuccess = 1;

                                    }
                                    else
                                    {
                                        report.SendFailure = 1;
                                        report.SendSuccess = 0;
                                    }

                                    InsertOperate<FundSms.Server.Model.Report>.Create(ds).Execute(report);
                                }

                                UpdateOperate<MT_TEST>.Create(ds).From(new Table("SMS_MT_" + account)).Fields(FieldValue.Create(MT_TEST._IsReport, true), FieldValue.Create(MT_TEST._LastUpdate, DateTime.Now)).Where(MT_TEST._LogID == test.LogID).Execute();

                                Output("[" + account + "][" + enterprisecode + "]" + test.Mobile + "更新");

                                ds.Commit();
                            }
                            catch (Exception e)
                            {
                                try { ds.RollBack(); }
                                catch { }

                                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);

                                Thread.Sleep(SleepTime);

                                continue;
                            }
                        }
                    }
                }

                Thread.Sleep(SleepTime);

            }

        }


        /// <summary>
        /// 定时管理线程
        /// </summary>
        private static void ManageThreads()
        {
            //判断是否有新企业
            if (CurrentEnterpriseCount < Enterprises.Count)
            {
                if (Enterprises.Count <= SupportEnterpriseCount)
                {
                    int dif = Enterprises.Count - CurrentEnterpriseCount;

                    for (int i = 0; i < dif; i++)
                    {
                        LogThreads[CurrentEnterpriseCount + i] = new Thread(new ParameterizedThreadStart(Log));
                        LogThreads[CurrentEnterpriseCount + i].Name = Enterprises[CurrentEnterpriseCount + i].EnterpriseCode;
                        LogThreads[CurrentEnterpriseCount + i].IsBackground = false;
                        LogThreads[CurrentEnterpriseCount + i].Start(Enterprises[CurrentEnterpriseCount + i]);

                        ThreadStatus.Add(Enterprises[CurrentEnterpriseCount + i].EnterpriseCode, false);
                    }

                    Output("新增企业数：" + dif, true);

                    CurrentEnterpriseCount = Enterprises.Count;

                    Output("当前企业数：" + CurrentEnterpriseCount, true);
                }

            }
        }

        #endregion

        #region 初始化服务设置
        protected override void OnStart(string[] args)
        {
            InitilizeCompoment();
        }

        protected override void OnStop()
        {
            //停止定时器
            timerConsole.Enabled = false;
            timerEnterprise.Enabled = false;

            //通知线程结束循环
            Stopped = true;

            while (!AllStop())
            {
                Thread.Sleep(SleepTime);
            }
        }

        /// <summary>
        /// 判断工作线程是否已经都停止了
        /// </summary>
        /// <returns></returns>
        private static bool AllStop()
        {
            try
            {
                lock (obj)
                {
                    foreach (bool value in ThreadStatus.Values)
                    {
                        if (!value)
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);

                return false;
            }
        }

        #endregion

        #region 初始化定时器
        /// <summary>
        /// 初始化定时器
        /// </summary>
        private static void InitilizeTimer()
        {
            // 定时清理控制台
            timerConsole.Interval = RefreshConsoleTime;
            timerConsole.Enabled = true;
            timerConsole.Elapsed += new System.Timers.ElapsedEventHandler(timerConsole_Elapsed);
            timerConsole.AutoReset = true;

            //定时刷新企业数据
            timerEnterprise.Interval = RefreshEnterpriseTime;
            timerEnterprise.Enabled = true;
            timerEnterprise.Elapsed += new System.Timers.ElapsedEventHandler(timerEnterprise_Elapsed);
            timerEnterprise.AutoReset = true;
        }

        static void timerEnterprise_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            IList<Enterprise> listenterprise = GetEnterprise();

            if (!listenterprise.Equals(Enterprises))
            {
                try
                {
                    Enterprises = listenterprise;

                    Output("企业数据已更新");

                    ManageThreads();
                }
                catch
                {
                }
            }
        }

        static void timerConsole_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Debug == 1)
            {
                Console.Clear();
                Output("控制台已更新");
            }
        }
        #endregion

        #region 数据源
        /// <summary>
        /// 获得所有企业
        /// </summary>
        /// <returns></returns>
        private static IList<Enterprise> GetEnterprise()
        {
            IList<Enterprise> listenterprise = QueryOperate<Enterprise>.Create(DataKey).Where(Enterprise._EnterpriseStatus == "normal").OrderBy(Enterprise._EnterpriseID).List();

            return listenterprise;
        }

        #endregion

        #region 调试辅助逻辑
        private static string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        private static void Output(string msg)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }
            }
        }

        private static void Output(string msg, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        FundSms.SmsLib.Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }
        }

        private static void Output(string msg, ConsoleColor color)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }
            }
        }

        private static void Output(string msg, ConsoleColor color, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        FundSms.SmsLib.Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }
        }
        #endregion
    }
}
